<template>
  <div>
    <!-- 功能按钮 -->
    <el-form class="tableSearch" size="mini">
      <el-form-item>
        <el-button type="primary" @click="$router.back(-1)">返回</el-button>
        <el-button type="primary" @click="submitForm('formdata')">保存</el-button>
        <el-button type="primary" @click="dialogPswVisible=true;">取来源单</el-button>
        <el-button type="primary" @click="selectTable.handleMultipleDel()">批量删除商品</el-button>
      </el-form-item>
    </el-form>

    <!-- form表单 -->
    <el-form :model="formdata" :rules="rules" ref="formdata" label-width="120px" size="mini">
      <el-row>
        <el-col :span="8">
          <el-form-item label="供应商：">
            <el-input v-model="formdata.supplierName" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收货状态：">
            <el-input v-model="purchaseReceivingsStatusArr[formdata.inStatus]" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="收货日期：" prop="receiveDate">
            <el-date-picker
              v-model="formdata.receiveDate"
              format="yyyy年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              type="date"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据日期：">
            <el-date-picker
              v-model="formdata.orderDate"
              format="yyyy年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              type="date"
              disabled
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="单据号：">
            <el-input v-model="formdata.purchaseinCode" placeholder="单据号自动生成" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="来源单号：">
            <el-input v-model="formdata.sourceNum" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格 -->
    <el-table :data="selectTable.tableData" @selection-change="selectTable.handleMultipleSelect">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="#" width="55"></el-table-column>
      <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
      <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
      <el-table-column prop="name" label="商品" align="center" width="200">
        <template slot-scope="scope">
          <span v-if="scope.row.goodsName!=undefined">{{scope.row.goodsName}}</span>
          <span v-else>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="goodsBatchNumber" label="商品批次" align="center" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.isBatch==1" v-show="!scope.row.showBatch">{{scope.row.goodsBatchNumber}}</span>
          <input
            class="commonInput"
            v-if="scope.row.isBatch==1"
            v-show="scope.row.showBatch"
            v-model="scope.row.goodsBatchNumber"
            size="mini"
            type="text"
            style="width:100px"
            value="1"
            min="0"
            maxlength="16"
            oninput="value=value.replace(/[\W]/g,'')"
            onafterpaste="value=value.replace(/[\W]/g,'')"
          />
          <span v-if="scope.row.isBatch === '0'">{{"---"}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="dateInProduced" label="生产日期" align="center" width="200">
        <template slot-scope="scope">
          <el-date-picker
            v-if="scope.row.isBatch==1"
            v-show="scope.row.showBatch"
            size="small"
            v-model="scope.row.dateInProduced"
            :picker-options="pickerOptions"
            format="yyyy年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            type="date"
          ></el-date-picker>
          <span v-if="scope.row.isBatch==1" v-show="!scope.row.showBatch">{{scope.row.dateInProduced}}</span>
          <span v-if="scope.row.isBatch === '0'">{{"---"}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="repositoryname" label="仓库" align="center" width="210">
        <template slot-scope="scope">
          <el-input v-model="scope.row.repositoryname" size="mini" disabled>
            <el-button
              class="buttonxz"
              type="primary"
              @click="openWareDialog(scope.$index)"
              slot="append"
            >选择</el-button>
          </el-input>
        </template>
      </el-table-column>
      <el-table-column prop="unitName" label="单位" align="center"></el-table-column>
      <el-table-column prop="goodsSpec" label="规格型号" align="center">
        <template slot-scope="scope">
          <div v-for="(item, index) in scope.row.goodsSpec" :key="index">
            <span>{{item.paramName}} :</span>
            <span>{{item.paramValue}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="goodsNum" label="数量" align="center" width="150">
        <template slot-scope="scope">
          <input
            class="commonInput"
            v-model="scope.row.arriveNum"
            size="mini"
            type="text"
            style="width:100px"
            value="1"
            min="0"
            maxlength="8"
            oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
            onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="text" @click="selectTable.handleSingleDel(scope.$index)" size="mini">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 费用表单 -->
    <el-form :model="formdata" label-width="120px" size="mini" style="margin-top:25px;">
      <el-row>
        <el-col :span="8">&nbsp;</el-col>
        <el-col :span="8">
          <el-form-item label="操作员：">
            <el-input v-model="formdata.creater" disabled></el-input>
          </el-form-item>
          <el-form-item label="备注：">
            <el-input v-model="formdata.remark" type="textarea" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">&nbsp;</el-col>
      </el-row>
    </el-form>

    <!-- 仓库选择弹出框 -->
    <el-dialog
      title="仓库选择"
      :visible.sync="warehouseClass.dialog"
      :closeOnClickModal="false"
      :closeOnPressEscape="false"
    >
      <el-form label-width="0" size="mini">
        <el-form-item>
          <el-button type="primary" @click="handleSelectWarehose()">选择</el-button>
          <el-button @click="warehouseClass.dialog=false">取消</el-button>
          <el-alert title="未录入期初库存仓库不可选择" type="warning" :closable="false" style="display:inline;"></el-alert>
        </el-form-item>
      </el-form>
      <el-table
        :data="warehouseClass.tableData"
        tooltip-effect="dark"
        highlight-current-row
        @current-change="warehouseClass.handleSingleSelect"
      >
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="repositoryName" label="仓库" align="center"></el-table-column>
        <el-table-column prop="repositoryAddress" label="地址" align="center"></el-table-column>
      </el-table>
      <page-unit :pageData="warehouseClass.pageData" :func="_getRepositoryListPage"></page-unit>
    </el-dialog>

    <!-- 采购选择弹出框 -->
    <el-dialog
      title="采购订单选择"
      :visible.sync="purchanseClass.dialog"
      :closeOnClickModal="false"
      :closeOnPressEscape="false"
    >
      <el-table
        :data="purchanseClass.tableData"
        tooltip-effect="dark"
        highlight-current-row
        @current-change="purchanseClass.handleSingleSelect"
      >
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="purchaseCode" label="单据编号" align="center"></el-table-column>
        <el-table-column prop="createTime" :formatter="tim" label="日期" align="center"></el-table-column>
        <el-table-column prop="supplierName" label="供应商" align="center"></el-table-column>
      </el-table>
      <page-unit :pageData="purchanseClass.pageData" :func="_getByShopId"></page-unit>
      <div class="operationBox tableSearch position-content">
        <el-button size="mini" type="primary" @click="handleSelectPurchase()">选择</el-button>
        <el-button size="mini" @click="purchanseClass.dialog=false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 销售出库单选择弹出框 -->
    <el-dialog
      title="销售出库单选择"
      :visible.sync="saleOutCalss.dialog"
      :closeOnClickModal="false"
      :closeOnPressEscape="false"
    >
      <el-table
        :data="saleOutCalss.tableData"
        tooltip-effect="dark"
        highlight-current-row
        @current-change="saleOutCalss.handleSingleSelect"
      >
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="outCode" label="单据编号" align="center"></el-table-column>
        <el-table-column prop="orderDate" :formatter="tim" label="日期" align="center"></el-table-column>
        <el-table-column prop="supplierName" label="供应商" align="center"></el-table-column>
      </el-table>
      <page-unit :pageData="saleOutCalss.pageData" :func="_getByShopId"></page-unit>
      <div class="operationBox tableSearch position-content">
        <el-button size="mini" type="primary" @click="handleSelectSaleOut()">选择</el-button>
        <el-button size="mini" @click="saleOutCalss.dialog=false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 取来源单弹窗 -->
    <el-dialog
      title="取来源单"
      :visible.sync="dialogPswVisible"
      :closeOnClickModal="false"
      :closeOnPressEscape="false"
      width="405px"
    >
      <el-form size="mini">
        <el-form-item label="来源单据:">
          <el-radio-group v-model="formdata.purchaseType" @change="radioChange">
            <el-radio label="1">销售出库单</el-radio>
            <el-radio label="2">采购订单</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="position-content">
          <el-input v-model="formdata.sourceNum">
            <el-button type="primary" @click="choseType()" slot="append">选择</el-button>
          </el-input>
        </el-form-item>
        <el-form-item class="position-content">
          <el-button type="primary" @click="determineVoucher()">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import pageUnit from "@/components/Page";
import SdInput from "@/components/SdInput";
import s from "@/util/state";
import u from "@/util";
import { TableHandle } from "@/util/class";
import {
  selectBaseShopPageList,
  findGoodsListPage,
  getRepositoryListPage,
  saveRepertoryInBound,
  getByShopId,
  getGoodsPurchaseDetails,
  getRepertoryOutBoundDetail
} from "@/api";

export default {
  components: { SdInput, pageUnit },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      }, //当前日期之后的不可选
      purchaseReceivingsStatusArr: s.purchaseReceivingsStatusArr, // 收货状态
      purchaseSourceId: "", // 采购订单id
      saleoutId: "", // 销售出库单来源单id
      cang_index: "", // 修改仓库的商品定位
      formdata: {
        supplierId: "", // 供应商id
        supplierName: "", // 供应商名称
        receiveDate: "", // 收货日期
        orderDate: "", // 单据日期
        purchaseinCode: "", // 单据编号
        remark: "", // 备注
        purchaseType: "", // 1:销售出库单，2:采购订单
        inStatus: 1, // 收货状态
        sourceNum: "" // 来源单号
      },
      dialogPswVisible: false, // 取来源单弹窗
      rules: {
        supplierName: [
          { required: false, message: "请选择供应商", trigger: "blur" }
        ],
        receiveDate: [
          { required: true, message: "请选择收货时间", trigger: "blur" }
        ]
      },
      saleOutCalss: new TableHandle(), // 销售出库单弹窗对象
      purchanseClass: new TableHandle(), // 采购订单弹窗对象
      warehouseClass: new TableHandle(), // 仓库弹窗对象
      selectTable: new TableHandle() // 来源单商品数组对象
    };
  },
  computed: mapState(["merchantId", "companyName", "linkName", "userId"]),
  mounted() {
    this.init();
  },
  methods: {
    tim(row) {
      return u.foryear(parseInt(row.createTime));
    },

    init() {
      this.formdata.orderDate = u.getNowFormatDate();
      this.formdata.purchaseinCode = "";
      this.formdata.creater = this.linkName;
    },

    // 获取仓库列表
    _getRepositoryListPage(pageSize, pageNum) {
      getRepositoryListPage({
        pageSize: pageSize,
        pageNum: pageNum,
        nameCode: "",
        status: 0,
        shopId: this.merchantId
      }).then(res => {
        this.warehouseClass.tableData = res.data.list;
        this.warehouseClass.pageData.totalItems = res.data.pageTotal;
      });
    },

    // 获取销售出库单或采购订单列表
    _getByShopId(pageSize, pageNum) {
      let data = {
        pageSize: pageSize,
        pageNum: pageNum,
        shopId: this.merchantId,
        purchaseType: ""
      };
      if (this.formdata.purchaseType == "2") {
        // 采购订单
        data.purchaseType = 2;
        data.statusFlow = 3;
      } else if (this.formdata.purchaseType == "1") {
        // 销售出库单
        data.purchaseType = 1;
      }
      getByShopId(data).then(res => {
        if (data.purchaseType == 1) {
          this.saleOutCalss.tableData = res.data.list;
          this.saleOutCalss.pageData.totalItems = res.data.pageTotal;
        }
        if (data.purchaseType == 2) {
          this.purchanseClass.tableData = res.data.list;
          this.purchanseClass.pageData.totalItems = res.data.pageTotal;
        }
      });
    },

    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleSave();
        } else {
          return false;
        }
      });
    },

    handleSave() {
      // ???
      if (this.formdata.receiveDate === undefined) {
        this.formdata.receiveDate = "";
      }

      if (this.selectTable.tableData.length == 0) {
        this.$message.error("商品不能为空");
        return false;
      }

      if (this.selectTable.tableData.some(i => i.arriveNum <= 0)) {
        this.$message.error("商品数量不能小于等于0");
        return false;
      }

      if (
        this.selectTable.tableData.some(i => {
          return i.warehouseId == "" || i.warehouseId == undefined;
        })
      ) {
        this.$message.error("仓库不能为空");
        return false;
      }

      if (
        this.selectTable.tableData.some(i => {
          return (
            i.isBatch == "1" &&
            (i.dateInProduced == "" ||
              i.dateInProduced == undefined ||
              i.dateInProduced == null) &&
            this.formdata.purchaseType == "2"
          );
        })
      ) {
        this.$message.error("选择生产日期");
        return false;
      }
      this.selectTable.tableData.forEach(i => {
        delete i.createTime;
        delete i.updateTime;
        i.goodsNum = i.arriveNum;
        i.goodsAmount=Number(i.goodsPrice) * Number(i.goodsNum)
        i.goodsDetailId=i.id;
      });
      let orderPurchaseId;
      if (this.formdata.purchaseType == "2") {
        orderPurchaseId = this.purchaseSourceId;
      } else if (this.formdata.purchaseType == "1") {
        orderPurchaseId = this.saleoutId;
      }
      saveRepertoryInBound({
        shopId: this.merchantId,
        shopName: this.companyName,
        orderPurchaseId: orderPurchaseId, // 来源单id
        orderDate: this.formdata.receiveDate,
        remark: this.formdata.remark,
        creater: this.userId,
        inType: 1, // 单据类型
        goodsList: JSON.stringify(this.selectTable.tableData),
        deliveryCode: this.formdata.sourceNum // 来源单号
      }).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg);
          u.routerTo("/order-center/purchase-management/purchase-receiptMg");
        }
      });
    },

    // 仓库弹窗点击选择
    handleSelectWarehose() {
      if (this.warehouseClass.isSelect(1, this, "请先选择仓库！")) {
        let i = this.cang_index;
        this.$set(
          this.selectTable.tableData[i],
          "repositoryname",
          this.warehouseClass.singleSelectTable.repositoryName
        );
        this.selectTable.tableData[
          i
        ].WarehouseName = this.warehouseClass.singleSelectTable.repositoryName;
        this.selectTable.tableData[
          i
        ].warehouseId = this.warehouseClass.singleSelectTable.id;
        this.warehouseClass.dialog = false;
      }
    },

    // 确定选择采购订单
    handleSelectPurchase() {
      if (this.purchanseClass.isSelect(1, this, "请先选择采购订单！")) {
        this.purchaseSourceId = this.purchanseClass.singleSelectTable.id;
        this.formdata.sourceNum = this.purchanseClass.singleSelectTable.purchaseCode;
        this.purchanseClass.dialog = false;
      }
    },

    // 确定选择销售出库单
    handleSelectSaleOut() {
      if (this.saleOutCalss.isSelect(1, this, "请先选择销售出库单！")) {
        this.saleoutId = this.saleOutCalss.singleSelectTable.id;
        this.formdata.sourceNum = this.saleOutCalss.singleSelectTable.outCode;
        this.saleOutCalss.dialog = false;
      }
    },

    // 获取采购订单详情
    _getGoodsPurchaseDetails() {
      getGoodsPurchaseDetails({
        id: this.purchaseSourceId,
        arriveNum: "1"
      }).then(res => {
        if (res.data != null) {
          let purchaseType = this.formdata.purchaseType;
          this.formdata = res.data;
          this.formdata.purchaseType = purchaseType;
          this.selectTable.tableData = res.data.goodsList;
          for (let i = 0; i < this.selectTable.tableData.length; i++) {
            this.selectTable.tableData[i].goodsNum = this.selectTable.tableData[
              i
            ].arriveNum;
            if (this.selectTable.tableData[i].isBatch === "1") {
              if (this.selectTable.tableData[i].goodsBatchNumber == undefined||this.selectTable.tableData[i].goodsBatchNumber == "") {
                this.selectTable.tableData[i].showBatch = true;
              } else {
                this.selectTable.tableData[i].showBatch = false;
              }
            }
          }
          this.formdata.receiveDate = u.getdatetime(this.formdata.receiveDate);
          this.formdata.orderDate = u.getdatetime(this.formdata.orderDate);
          this.formdata.inStatus = 1;
          this.formdata.sourceNum = res.data.purchaseCode;
          this.formdata.creater = res.data.userName;
          this.formdata.remark = "基于单号：" + this.formdata.sourceNum;
        }
      });
    },

    // 取销售出库单详情
    _getRepertoryOutBoundDetail() {
      getRepertoryOutBoundDetail({
        id: this.saleoutId,
        shopId:this.merchantId,
        arriveNum: "1"
      }).then(res => {
        if (res.data != null) {
          let purchaseType = this.formdata.purchaseType;
          this.formdata = res.data;
          this.formdata.purchaseType = purchaseType;
          this.formdata.inStatus = 1;
          this.selectTable.tableData = res.data.goodsList;
          this.selectTable.tableData.forEach(i => {
            i.goodsNum = i.arriveNum;
            if (
              i.isBatch == 1 &&
              (i.goodsBatchNumber == "" || i.goodsBatchNumber == undefined) &&
              (i.dateInProduced == undefined || i.dateInProduced == "")
            ) {
              i.showBatch = true;
            } else {
              i.showBatch = false;
            }
          });
          this.formdata.sourceNum = res.data.outCode;
          this.formdata.orderDate = u.getdatetime(this.formdata.orderDate);
          this.formdata.creater = res.data.userName;
          this.formdata.remark = "基于单号：" + this.formdata.outCode;
        }
      });
    },

    // 点击打开仓库弹窗
    openWareDialog(index) {
      this.cang_index = index;
      this.warehouseClass.dialog = true;
      this._getRepositoryListPage(this.warehouseClass.pageData.pageSize, 1);
    },

    /**
     * 选择来源单类型
     * 先判断是否选择了销售出库单或采购订单
     */
    choseType() {
      if (this.formdata.purchaseType == "2") {
        // 采购订单
        this.purchanseClass.dialog = true;
        this._getByShopId(this.purchanseClass.pageData.pageSize, 1);
      } else if (this.formdata.purchaseType == "1") {
        // 销售出库单
        this.saleOutCalss.dialog = true;
        this._getByShopId(this.saleOutCalss.pageData.pageSize, 1);
      }
    },

    /**
     * 取来源单确定
     * 判断是否选择了订单和来源单号
     */
    determineVoucher() {
      if (this.formdata.sourceNum == "") {
        // 来源单号是否为空
        this.$message.error("请选择来源单!");
      } else {
        if (this.formdata.purchaseType != "") {
          this.dialogPswVisible = false;
          if (this.formdata.purchaseType == "2") {
            this._getGoodsPurchaseDetails(); // 获取采购订单详情
          } else if (this.formdata.purchaseType == "1") {
            this._getRepertoryOutBoundDetail(); // 获取销售出库单详情
          }
        }
      }
    },

    radioChange(val) {
      this.formdata.sourceNum = "";
    }
  }
};
</script>

<style lang="less">
.position-content {
  text-align: right;
  margin-right: 30px;
}

.el-input-group__append {
  background-color: #409eff;
  border-color: #409eff;
  color: #ffffff;
}

.el-dialog__header {
  background-color: #25a0e9;
  .el-dialog__title {
    color: #ffffff;
  }
  .el-dialog__close {
    color: #ffffff;
    &:hover {
      &:before {
        color: #ffffff;
      }
    }
  }
}
</style>
